import { observe } from "./observe.mjs";

const arrayPrototype = Array.prototype;

const arrayMethod = Object.create(arrayPrototype);

const methodNames = ['unshift', 'shift', 'push', 'pop', 'splice', 'reverse', 'sort'];

for (let methodName of methodNames) {
    const original = arrayPrototype[methodName];
    Object.defineProperty(arrayMethod, methodName, {
        enumerable: true,
        configurable: true,
        writable: true,
        value(...args) {
            let addedItems;
            switch (methodName) {
                case 'splice':
                    addedItems = args.slice(2);
                    break;
                case 'push':
                case 'unshift':
                    addedItems = args.slice();
            }
            if (Array.isArray(addedItems)) {
                addedItems.forEach(observe)
            }
            const result = original.apply(this, args);
            this.__ob__.dep.notify();
            return result;
        }
    })
}

export default arrayMethod;